package at.fhj.itm11.forum.data;

import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import at.fhj.itm11.forum.model.Topic;



@RequestScoped
public class TopicListProducer {
	
	@Inject
    private EntityManager em;
	private List<Topic> topics;

	@Produces
	@Named
	public List<Topic> getTopics() {
		this.retrieveAllTopicsOrderedByTitle();
		return topics;
	}

	public void retrieveAllTopicsOrderedByTitle() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Topic> criteria = cb.createQuery(Topic.class);
		Root<Topic> topic = criteria.from(Topic.class);
		criteria.select(topic).orderBy(cb.asc(topic.get("title")));
		topics = em.createQuery(criteria).getResultList();
	}
}
